package com.ahdy.controller;

import com.ahdy.service.DebugDeepSeekService;
import com.ahdy.service.DeepSeekService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/deepseek")
@CrossOrigin
public class DeepSeekController {

    @Autowired
    private DeepSeekService deepSeekService;

    // 添加调试服务
    @Autowired(required = false)
    private DebugDeepSeekService debugDeepSeekService;

    /**
     * 流式AI问答接口（推荐）- 优化字符编码
     * 前端使用fetch读取流式数据
     */
    @GetMapping(value = "/ask-stream", produces = MediaType.TEXT_PLAIN_VALUE + ";charset=UTF-8")
    public ResponseEntity<Flux<String>> askStream(@RequestParam String question) {
        log.info("收到流式AI请求，问题长度: {} 字符", question.length());

        // 参数验证
        if (question == null || question.trim().isEmpty()) {
            return ResponseEntity.badRequest()
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE + ";charset=UTF-8")
                    .body(Flux.just("错误：问题不能为空"));
        }

        if (question.length() > 4000) {
            return ResponseEntity.badRequest()
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE + ";charset=UTF-8")
                    .body(Flux.just("错误：问题长度不能超过4000字符"));
        }

        Flux<String> responseFlux = deepSeekService.callDeepSeekStream(question.trim())
                .filter(content -> content != null && !content.trim().isEmpty())
                .map(content -> {
                    // 确保内容是UTF-8编码
                    try {
                        byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
                        String utf8Content = new String(bytes, StandardCharsets.UTF_8);
                        log.debug("发送内容块: {}", utf8Content.length() > 20 ?
                                utf8Content.substring(0, 20) + "..." : utf8Content);
                        return utf8Content;
                    } catch (Exception e) {
                        log.warn("字符编码处理失败: {}", e.getMessage());
                        return content;
                    }
                })
                .doOnSubscribe(subscription -> log.info("开始流式传输"))
                .doOnError(error -> log.error("流式传输错误: {}", error.getMessage()))
                .doOnComplete(() -> log.info("流式传输完成"))
                .onErrorResume(error -> Flux.just("错误：AI服务暂时不可用 - " + error.getMessage()))
                .timeout(Duration.ofMinutes(2)); // 2分钟超时

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE + ";charset=UTF-8")
                .header(HttpHeaders.CACHE_CONTROL, "no-cache")
                .header(HttpHeaders.CONNECTION, "keep-alive")
                .header("Access-Control-Allow-Origin", "*")
                .header("Access-Control-Allow-Headers", "Content-Type")
                .body(responseFlux);
    }

    /**
     * SSE格式的流式接口（用于支持SSE的前端）- 优化字符编码
     */
    @GetMapping(value = "/ask-sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE + ";charset=UTF-8")
    public ResponseEntity<Flux<ServerSentEvent<String>>> askSSE(@RequestParam String question) {
        log.info("收到SSE AI请求，问题长度: {} 字符", question.length());

        if (question == null || question.trim().isEmpty()) {
            Flux<ServerSentEvent<String>> errorFlux = Flux.just(ServerSentEvent.<String>builder()
                    .event("error")
                    .data("问题不能为空")
                    .build());
            return ResponseEntity.badRequest()
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE + ";charset=UTF-8")
                    .body(errorFlux);
        }

        Flux<ServerSentEvent<String>> sseFlux = deepSeekService.callDeepSeekStream(question.trim())
                .filter(content -> content != null && !content.trim().isEmpty())
                .map(content -> {
                    // 确保内容是UTF-8编码
                    String utf8Content = ensureUtf8(content);
                    return ServerSentEvent.<String>builder()
                            .event("message")
                            .data(utf8Content)
                            .build();
                })
                .concatWith(Flux.just(ServerSentEvent.<String>builder()
                        .event("complete")
                        .data("[DONE]")
                        .build()))
                .doOnError(error -> log.error("SSE传输错误: {}", error.getMessage()))
                .onErrorResume(error -> Flux.just(ServerSentEvent.<String>builder()
                        .event("error")
                        .data("AI服务暂时不可用: " + error.getMessage())
                        .build()))
                .timeout(Duration.ofMinutes(2));

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE + ";charset=UTF-8")
                .header(HttpHeaders.CACHE_CONTROL, "no-cache")
                .header(HttpHeaders.CONNECTION, "keep-alive")
                .header("Access-Control-Allow-Origin", "*")
                .header("Access-Control-Allow-Headers", "Content-Type")
                .body(sseFlux);
    }

    /**
     * 非流式AI问答接口（用于简单场景）- 优化字符编码
     */
    @PostMapping(value = "/ask", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public Mono<ResponseEntity<Map<String, Object>>> ask(@RequestBody Map<String, String> request) {
        String question = request.get("question");
        log.info("收到非流式AI请求，问题长度: {} 字符", question != null ? question.length() : 0);

        // 参数验证
        if (question == null || question.trim().isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "问题不能为空");
            return Mono.just(ResponseEntity.badRequest()
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
                    .body(errorResponse));
        }

        if (question.length() > 4000) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "问题长度不能超过4000字符");
            return Mono.just(ResponseEntity.badRequest()
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
                    .body(errorResponse));
        }

        return deepSeekService.callDeepSeekSimple(question.trim())
                .map(answer -> {
                    // 确保答案是UTF-8编码
                    String utf8Answer = ensureUtf8(answer);

                    Map<String, Object> response = new HashMap<>();
                    response.put("success", true);
                    response.put("question", ensureUtf8(question));
                    response.put("answer", utf8Answer);
                    response.put("timestamp", System.currentTimeMillis());
                    response.put("answerLength", utf8Answer.length());

                    log.info("非流式请求完成，回答长度: {} 字符", utf8Answer.length());
                    return ResponseEntity.ok()
                            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
                            .body(response);
                })
                .onErrorResume(error -> {
                    log.error("非流式请求失败: {}", error.getMessage());
                    Map<String, Object> errorResponse = new HashMap<>();
                    errorResponse.put("success", false);
                    errorResponse.put("message", "AI服务暂时不可用: " + error.getMessage());
                    errorResponse.put("timestamp", System.currentTimeMillis());
                    return Mono.just(ResponseEntity.status(500)
                            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
                            .body(errorResponse));
                })
                .timeout(Duration.ofMinutes(2));
    }

    /**
     * 确保字符串是UTF-8编码的辅助方法
     */
    private String ensureUtf8(String input) {
        if (input == null) {
            return "";
        }

        try {
            // 检测并转换字符编码
            byte[] bytes = input.getBytes(StandardCharsets.UTF_8);
            return new String(bytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.warn("字符编码转换失败: {}", e.getMessage());
            return input;
        }
    }

    /**
     * 健康检查接口
     */
    @GetMapping(value = "/health", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> response = new HashMap<>();
        response.put("status", "healthy");
        response.put("service", "DeepSeek AI Service");
        response.put("timestamp", System.currentTimeMillis());
        response.put("version", "2.1.0");
        response.put("encoding", "UTF-8");

        Map<String, String> endpoints = new HashMap<>();
        endpoints.put("stream", "GET /ask-stream?question=你好");
        endpoints.put("sse", "GET /ask-sse?question=你好");
        endpoints.put("simple", "POST /ask {\"question\":\"你好\"}");
        response.put("endpoints", endpoints);

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
                .body(response);
    }

    /**
     * 获取模型信息
     */
    @GetMapping(value = "/model-info", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public ResponseEntity<Map<String, Object>> getModelInfo() {
        Map<String, Object> response = new HashMap<>();
        response.put("model", "deepseek-chat");
        response.put("provider", "DeepSeek");
        response.put("capabilities", new String[]{"chat", "stream", "chinese", "english"});
        response.put("maxTokens", 4000);
        response.put("supportedFormats", new String[]{"text/plain", "text/event-stream", "application/json"});
        response.put("encoding", "UTF-8");

        Map<String, String> features = new HashMap<>();
        features.put("textCleaning", "自动移除data前缀和格式化");
        features.put("streaming", "支持实时流式传输");
        features.put("errorHandling", "完善的错误处理和重试机制");
        features.put("timeout", "2分钟请求超时保护");
        features.put("encoding", "UTF-8字符编码支持");
        response.put("features", features);

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
                .body(response);
    }

    /**
     * 调试接口 - 详细记录编码问题
     */
    @GetMapping(value = "/debug-stream", produces = MediaType.TEXT_PLAIN_VALUE + ";charset=UTF-8")
    public ResponseEntity<Flux<String>> debugStream(@RequestParam String question) {
        log.info("收到调试请求: {}", question);

        if (debugDeepSeekService == null) {
            return ResponseEntity.ok()
                    .body(Flux.just("调试服务未启用，请添加DebugDeepSeekService"));
        }

        Flux<String> responseFlux = debugDeepSeekService.callDeepSeekStreamDebug(question)
                .doOnNext(content -> log.info("调试输出: {}", content));

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE + ";charset=UTF-8")
                .body(responseFlux);
    }
}
